import 'dart:convert';
import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/cg_umeng_analysis.dart';
import 'package:yp/config/config.dart';
import 'package:yp/config/event_bus.dart';
import 'package:yp/pages/trolley/trolley_logic.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:yp/utils/util.dart';
import 'package:intl/intl.dart';

import '../../helper.dart';
import 'state.dart';
import 'dart:developer';

import '../coupon_association/shopping_voucher_dialog.dart';

class MainLogic extends GetxController {
  final state = MainState();
  RxInt cartItemsNum = Get.put(TrolleyLogic()).cartItemsNum;
  AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  @override
  // ignore: must_call_super
  void onInit() {
    super.onInit();
    print('---------底部初始化-------------');
    if (kIsWeb) {
      webpay("${Config.WEB_DOWN_URL}download.html");
    }

    /// 重新进入程序时, 清除第三方数据
    if (Get.arguments == null ||
        Get.arguments != null &&
            Get.arguments['shoppingCart'] == null &&
            Get.arguments['isChangeShop'] != true) {
      SpUtil.putInt(Config.IS_CHANGE_SHOP, 0);
      SpUtil.remove(Config.GET_SHOP_INFO);
    }
    _initPackage();
  }

  _initPackage() async {
    if (!kIsWeb) {
      initUmengAnalytics();
      Config.AMap_ios_get = Config.AMap_ios;
      if (GetPlatform.isIOS) {
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        var packageName = packageInfo.packageName;
        if (packageName == 'com.zrhsh') {
          Config.AMap_ios_get = Config.AMap_ios_com;
        }
      }
      AMapFlutterLocation.setApiKey(Config.AMap_andriod, Config.AMap_ios_get);

      fluwx.registerWxApi(
        appId: Config.WECHAT_APPID,
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: Config.UNIVERSAL_LINK,
      );
      fluwx.weChatResponseEventHandler.listen((event) {
        if (event is fluwx.WeChatLaunchMiniProgramResponse) {
          /// 取消支付：extMsg:{"errMsg":"requestPayment:fail cancel","status":"30"}
          /// 支付成功 extMsg:{"errMsg":"requestPayment:ok","status":"20"}
          /// {\"status\":\"30\",\"errMsg\":\"支付出错:INVALID_REQUEST-b_mch_id与b_aid不匹配\"}
          Map resultMap = json.decode(event.extMsg);
          print("支付结果");
          print("支付结果回来了====10==${event.extMsg.toString()}");
          print(SpUtil.getString('dingdan'));
          if (resultMap != null) {
            if (resultMap["status"].toString() == "20") {
              toast("支付成功");
              setMoneyOver(
                  SpUtil.getString('dingdan'), 1, 'Complete', 'success', 'a');
            } else {
              toast("支付失败");
              setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'a');
            }
          } else {
            setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'a');

            toast("支付失败");
          }
        }
      });
    }
  }

  @override
  void onReady() {
    super.onReady();
    switchTap(0);
    // 调用 eventBus.fir 发送事件信息
    eventBus.fire(EventFn());
    if (Get.arguments != null) {
      if (Get.arguments['shoppingCart'] == '2') {
        switchTap(2);
      }
    }
    if (!kIsWeb) {
      state.isShow.value = !SpUtil.getBool("isAgree", defValue: false);

      // if (!isAgree) {
      //   _agreementDialog();
      // }
    }
    print('进入首页数据');
  }

  getHomeCouponDataHandle() {
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };
    print('首页优惠券参数--${params}');
    Api.getHomeCouponData(params).listen((event) {
      log('首页优惠券数据返回----${event}');
      if (event['code'] == 0) {
        List listTemp = event['coupons'] ?? [];
        print('列表listTemp:${listTemp}');
        List couponsList = [];
        if (listTemp.length > 0) {
          listTemp.forEach((item) {
            if (item['use_begin_date'] != null &&
                item['use_begin_end'] != null) {
              couponsList.add({
                'coupon_id': item['coupon_id'],
                'qty': item['qty'],
                'title': item['title'],
                'sdate': item['use_begin_date'],
                'edate': item['use_begin_end'],
                'use_begin_date':
                    '${DateFormat("yyyy.MM.dd").format(DateTime.tryParse(item['use_begin_date']))}',
                'use_begin_end':
                    '${DateFormat("yyyy.MM.dd").format(DateTime.tryParse(item['use_begin_end']))}',
                'fixed_begin_term': item['fixed_begin_term'],
                'fixed_term': item['fixed_term'],
                'coupontype': item['coupontype'],
                'face_value': item['face_value'],
                'least_cost': item['least_cost'],
                'use_platform': item['use_platform'],
                'award_type': item['award_type'],
                'award_name': item['award_name']
              });
            } else {
              couponsList.add({
                'coupon_id': item['coupon_id'],
                'qty': item['qty'],
                'title': item['title'],
                'use_begin_date': null,
                'use_begin_end': null,
                'fixed_begin_term': item['fixed_begin_term'],
                'fixed_term': item['fixed_term'],
                'coupontype': item['coupontype'],
                'face_value': item['face_value'],
                'least_cost': item['least_cost'],
                'use_platform': item['use_platform'],
                'award_type': item['award_type'],
                'award_name': item['award_name']
              });
            }
          });
          print('数据处理后:${couponsList}');
          Future.delayed(Duration.zero, () {
            ShoppingVoucherDialog.showShoppingVoucherDialog(
                Get.context, couponsList, couponsList.length, false);
          });
        }
      }
    });
  }

  getCartNum() {
    var params2 = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      'access_token': SpUtil.getString('token'),
    };
    print('==========  params2 = $params2');
    //购物车商品件数
    Api.cartItemNum(params2).listen((event) {
      print('!!!!!!!!!!!!!!!!!!!');
      var cartNum = (event["number"] ?? 0).toString().split('.');
      // state.cartNum = cartNum[0];
      // print(state.cartNum);
      // // 购物车不同商品数量同步
      cartItemsNum.value = event["variety"];
      update();
    });
  }

  ///change tab
  void switchTap(int index) {
    var token = SpUtil.getString('token');
    if ((index == 2 || index == 3 || index == 4) && token == '') {
      Get.toNamed(RouteConfig.mallLogin);
    }
    if (index == 0) {
      getHomeCouponDataHandle();
      // 只允许首页打开爆屏广告
      SpUtil.putBool('closeAdvertise', false);
    } else {
      SpUtil.putBool('closeAdvertise', true);
    }

    if (index == 2 || index == 3) {
      if (SpUtil.getString('token') == null ||
          SpUtil.getString('token').isEmpty) {
        Get.toNamed(RouteConfig.mallLogin);
        return;
      }
    }
    state.selectedIndex.value = index;
    state.pageController.jumpToPage(index);
  }

  _agreementDialog() {
    showDialog(
      context: Get.context,
      barrierDismissible: false,
      builder: (ctx) {
        return SimpleDialog(
          title: Text(
            '个人信息保护',
            style: TextStyle(
              color: Color(0xff030303),
              fontSize: setWidth(28),
              fontWeight: FontWeight.w600,
            ),
            textAlign: TextAlign.center,
          ),
          titleTextStyle: TextStyle(
              fontSize: 16, fontWeight: FontWeight.bold, color: Colors.blue),
          children: [
            Column(
              children: [
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: setWidth(30),
                  ),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(100)),
                      color: Colors.white),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('感谢您对壹品慧一直以来的信任！'),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Container(
                        child: RichText(
                          text: TextSpan(
                            children: [
                              TextSpan(
                                text: '我们依据最新的监管要求更新了',
                                style: TextStyle(
                                  color: Color(0xff999999),
                                  fontSize: setWidth(22),
                                ),
                              ),
                              TextSpan(
                                  text: '《壹品慧隐私权政策》',
                                  style: TextStyle(
                                    color: Color(0xffEA5504),
                                    fontSize: setWidth(22),
                                  ),
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      Get.toNamed(RouteConfig.webview,
                                          arguments: {
                                            "url":
                                                "https://img.zrhsh.com/zrhshgg/treaty/yszc-yph.html",
                                          });
                                    }),
                              TextSpan(
                                text: '和',
                                style: TextStyle(
                                  color: Color(0xff999999),
                                  fontSize: setWidth(22),
                                ),
                              ),
                              TextSpan(
                                text: '《壹品慧服务协议》',
                                style: TextStyle(
                                  color: Color(0xffEA5504),
                                  fontSize: setWidth(22),
                                ),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    Get.toNamed(RouteConfig.webview,
                                        arguments: {
                                          "url":
                                              "http://img.zrhsh.com/zrhshgg/treaty/fwxy-20220113.html",
                                        });
                                  },
                              ),
                              TextSpan(
                                text: '（点击了解更新后的详细内容），特向您说明如下：',
                                style: TextStyle(
                                  color: Color(0xff999999),
                                  fontSize: setWidth(22),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Text(
                        '1、为向您提供缴费相关基本功能，我们会收集、使用必要的信息；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '2、为保障您的账号与使用安全，您需要授权我们读取本机识别码，您有权拒绝或取消授权，取消后不会影响您使用我们提供的其他服务；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '3、为在慧生活APP首页向您展示所在位置附近营业厅信息，您需要授权我们获取您的位置权限，您有权拒绝或取消授权，取消后不会影响您使用我们提供的其他服务；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '4、我们会采取业界先进的安全措施保护您的信息安全；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '5、未经您同意，我们不会从第三方处获取、共享或向其提供您的信息；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '6、您可以查询、更正您的个人信息；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '7、您如果选择不同意，则默认退出当前APP',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(40),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: setWidth(30)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        onTap: () async {
                          exit(0);
                        },
                        child: Container(
                          width: setWidth(200),
                          height: setWidth(60),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(
                              Radius.circular(100),
                            ),
                            border: Border.all(color: Color(0xff666666)),
                          ),
                          child: Center(
                            child: Text(
                              "不同意",
                              style: TextStyle(
                                fontSize: setWidth(24),
                                color: Color(0xff666666),
                              ),
                            ),
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          SpUtil.putBool("isAgree", true);
                          eventBus.fire(InitPackage());
                          Get.back();
                        },
                        child: Container(
                          width: setWidth(200),
                          height: setWidth(60),
                          decoration: BoxDecoration(
                            color: Color(0xffEA5504),
                            borderRadius: BorderRadius.all(
                              Radius.circular(100),
                            ),
                            border: Border.all(color: Color(0xffEA5504)),
                          ),
                          child: Center(
                            child: Text(
                              "同意",
                              style: TextStyle(
                                fontSize: setWidth(24),
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                )
              ],
            )
          ],
          backgroundColor: Colors.white,
          elevation: 10,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        );
      },
    );
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    /// 获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      /// 已经授权
      return true;
    } else {
      /// 未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  //
}
